package org.ktpro.shortlink.admin.config;

import org.ktpro.shortlink.admin.common.biz.user.RequestHeaderContextInterceptor;
import org.ktpro.shortlink.admin.common.biz.user.UserFlowRiskControlFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 用户配置自动装配
 */
@Configuration
public class UserConfiguration implements WebMvcConfigurer {

    /**
     * 用户信息传递拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestHeaderContextInterceptor()).addPathPatterns("/**");
    }

//    /**
//     * 用户信息传递过滤器
//     */
//    @Bean
//    public FilterRegistrationBean<UserTransmitFilter> globalUserTransmitFilter(StringRedisTemplate stringRedisTemplate) {
//        FilterRegistrationBean<UserTransmitFilter> registration = new FilterRegistrationBean<>();
//        registration.setFilter(new UserTransmitFilter());
//        registration.addUrlPatterns("/*");
//        registration.setOrder(0);        //序号越小，执行顺序越前
//        return registration;
//    }

    /**
     * 用户操作流量风控过滤器
     * 顺序在用户信息拦截器下，当用户拦截器搞定用户上下文后，下面的过滤器就可以拿到用户信息，判断后决定是否进行流量控制
     */
    @Bean
    @ConditionalOnProperty(name = "short-link.flow-limit.enable", havingValue = "true")
    public FilterRegistrationBean<UserFlowRiskControlFilter> globalUserFlowRiskControlFilter(
        StringRedisTemplate stringRedisTemplate,
        UserFlowRiskControlConfiguration userFlowRiskControlConfiguration) {
        FilterRegistrationBean<UserFlowRiskControlFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new UserFlowRiskControlFilter(stringRedisTemplate, userFlowRiskControlConfiguration));
        registration.addUrlPatterns("/*");
        registration.setOrder(10);
        return registration;
    }
}
